package com.zang.blogz.exception;

import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.hutool.json.JSONException;
import com.zang.blogz.constant.SecurityConstant;
import com.zang.blogz.result.AjaxJson;
import com.zang.blogz.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 *@author VampireAchao &lt; achao1441470436@gmail.com &gt; <br/> ZVerify &lt; 2556450572@qq.com &gt;
 * @author 臧臧 on 2022/6/17
 */
@ControllerAdvice
public class GlobalException {

    @Autowired
    private ApplicationContext applicationContext;

    // 全局异常拦截（拦截项目中的所有异常）
    @ResponseBody
    @ExceptionHandler
    public Result<?> handlerException(Exception e, HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        // 打印堆栈，以供调试
        System.out.println("全局异常---------------");
        e.printStackTrace();

        // 不同异常返回不同状态码
        Result<?> result = new Result<>();

        if (e instanceof NotLoginException) {

            NotLoginException ee = (NotLoginException) e;

            String ex = String.valueOf(ee);
            String substring = ex.substring(ex.indexOf(":"));

            result = Result.error(AjaxJson.CODE_NOT_LOGIN, substring);
        }else if (e instanceof JSONException) {

            JSONException ee = (JSONException) e;

            result = Result.error(AjaxJson.CODE_ERROR, SecurityConstant.Info.JSON_EXCEPTION);


        } else if (e instanceof NotRoleException) {

            NotRoleException ee = (NotRoleException) e;

            result = Result.error(AjaxJson.CODE_NOT_ROLE, String.format(SecurityConstant.Info.NOT_ROLE_EXCEPTION, ee.getRole()));

        } else if (e instanceof NotPermissionException) {

            NotPermissionException ee = (NotPermissionException) e;

            result = Result.error(AjaxJson.CODE_NOT_JUR, SecurityConstant.Info.NOT_PERMISSION_EXCEPTION);


        } else if (e instanceof DisableLoginException) {

            DisableLoginException ee = (DisableLoginException) e;

            result = Result.error(AjaxJson.CODE_IS_DISABLE_LOGIN, String.format(SecurityConstant.Info.DISABLE_LOGIN_EXCEPTION, ee.getDisableTime()));

        } else {    // 普通异常, 输出：500 + 异常信息

            result = Result.error(AjaxJson.CODE_ERROR,e.getMessage());


        }



        // 返回给前端
        return result;
    }
}